package com.deercrowing.takeaway.common.util;

import com.deercrowing.takeaway.common.properties.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.Map;

@Slf4j
@Configuration
@EnableConfigurationProperties({JwtProperties.class})
public class JwtUtil {

    public static String BuildToken(String secretKey, Integer minute, Map<String,Object> claims){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        // 分钟转换成毫秒
        long Expiration = System.currentTimeMillis() + minute * 60 * 1000;
        Date date = new Date(Expiration);

        String token = Jwts.builder()
                .setClaims(claims)
                .setExpiration(date)
                .signWith(signatureAlgorithm,secretKey)
                .compact();

        log.info("token:{}",token);
        return token;
    }

    public static Claims ParseToken(String secretKey, String token){

        Claims parse = Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(token)
                .getBody();

        log.info("info{}",parse);
        return parse;
    }
}
